package com.luyu.listener;

import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * 处理账户输入密码错误需要做的事情
 */
@Component
public class AccountLockListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
        String name = event.getAuthentication().getName();
        if (StrUtil.isNotBlank(name)){
            Integer errorNum=1;
            if (redisTemplate.hasKey(name)){
                 errorNum = Integer.valueOf(redisTemplate.opsForValue().get(name).toString())+1;
            }
            redisTemplate.opsForValue().set(name, errorNum, Duration.ofDays(1));
        }
    }
}
